package org.happy.tester.common.http;

import okhttp3.*;

import java.util.Map;

/**
 * Description
 *
 * @author baijingchuan
 * Date 2020/6/10
 **/
public class OkHttpRequestProvider {

    private static final String DEFAULT_PATH = "";

    private static final String DEFAULT_CONTENT_TYPE = "application/json;charset=utf-8";

    private String path;

    private Map<String, String> headers;

    private String rootPath;

    public Request postFormRequest(Map<String, String> paramMap) {
        HttpUrl httpUrl = initHttpUrlBuilder().build();
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> param : paramMap.entrySet()) {
            builder.add(param.getKey(), param.getValue());
        }
        FormBody formBody = builder.build();
        Request request = new Request.Builder()
                .post(formBody)
                .url(httpUrl)
                .headers(headers == null ? new Headers.Builder().build() : Headers.of(headers))
                .build();
        return request;
    }

    public Request postJsonRequest(String paramJson) {
        HttpUrl httpUrl = initHttpUrlBuilder().build();
        Request request = new Request.Builder()
                .post(RequestBody.create(paramJson, MediaType.parse(DEFAULT_CONTENT_TYPE)))
                .url(httpUrl)
                .headers(headers == null ? new Headers.Builder().build() : Headers.of(headers))
                .build();
        return request;
    }

    public Request getRequest(Map<String, String> paramMap) {
        HttpUrl.Builder urlBuilder = initHttpUrlBuilder();
        for (Map.Entry<String, String> param : paramMap.entrySet()) {
            urlBuilder.setQueryParameter(param.getKey(), param.getValue());
        }
        //headers.put("Content-Type", "application/json;charset=utf-8");
        HttpUrl httpUrl = urlBuilder.build();
        Request request = new Request.Builder()
                .url(httpUrl)
                .headers(headers == null ? new Headers.Builder().build() : Headers.of(headers))
                .get()
                .build();
        return request;
    }

    private HttpUrl.Builder initHttpUrlBuilder() {
        HttpUrl.Builder urlBuilder = HttpUrl.parse(rootPath).newBuilder().encodedPath(path);
        return urlBuilder;
    }


    public String getPath() {
        return path == null ? DEFAULT_PATH : path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public Map<String, String> getHeaders() {
        return headers;
    }

    public void setHeaders(Map<String, String> headers) {
        this.headers = headers;
    }

    public String getRootPath() {
        return rootPath;
    }

    public void setRootPath(String rootPath) {
        this.rootPath = rootPath;
    }
}
